package com.sk.skplanet.commute.actions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.sk.skplanet.commute.exceptions.BusAPIException;
import com.sk.skplanet.commute.vo.BusServerVo;
import com.sk.skplanet.commute.vo.Data;
import com.sk.skplanet.commute.vo.Point;
import com.sk.skplanet.commute.vo.Route;
import com.sk.skplanet.commute.vo.StopInfo;

public class DeleteTask extends AsyncTask<View, String, Boolean> {
	private ProgressDialog dialog;
	private Route route;
	private Point point;
	private StopInfo stopInfo;
	private Context context;
	private LinearLayout view;

	private JSONObject result;

	public DeleteTask(Context context, BusServerVo vo) {
		this.context = context;

		if (vo instanceof Route) this.route = (Route) vo;
		else if (vo instanceof Point) this.point = (Point) vo;
		else this.stopInfo = (StopInfo) vo;
	}

	@Override
	protected Boolean doInBackground(View... params) {
		view = (params.length > 0) ? (LinearLayout) params[0] : null;
		Vector<NameValuePair> nameValue = new Vector<NameValuePair>();
		nameValue.add(new BasicNameValuePair("auth_key", Data.AUTH_KEY));

		try {
			if (stopInfo != null) {
				nameValue.add(new BasicNameValuePair("stopinfo_id", Long.toString(stopInfo.getId())));
				result = getJSON(Data.URL_DEFAULT + Data.URL_DELSTOPINFO, nameValue);
			} else if (point != null) {
				nameValue.add(new BasicNameValuePair("point_id", Long.toString(point.getId())));
				result = getJSON(Data.URL_DEFAULT + Data.URL_DELPOINT, nameValue);
			} else if (route != null) {
				nameValue.add(new BasicNameValuePair("route_id", Long.toString(route.getId())));
				result = getJSON(Data.URL_DEFAULT + Data.URL_DELROUTE, nameValue);
			}
		} catch (BusAPIException e) {
			e.printStackTrace();
			return false;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	protected void onPostExecute(Boolean success) {
		super.onPostExecute(success);
		LinearLayout layout_location_list = (LinearLayout) view.getParent();
		layout_location_list.removeView(view);

		if (result != null) {
			try {
				long id = 0;
				if (route != null) {
					id = route.getId();
					List<Route> routeList = Data.memberData.getRoutes();
					for (Route r : routeList) {
						if (id == r.getId()) routeList.remove(r);
					}
				} else if (point != null) {
					id = point.getId();
					List<Route> routeList = Data.memberData.getRoutes();
					for (Route r : routeList) {
						List<Point> pointList = r.getPoints();
						for (Point p : pointList) {
							if (id == p.getId()) {
								pointList.remove(p);
							}
						}
					}
				} else if (stopInfo != null) {
					id = stopInfo.getId();
					List<Route> routeList = Data.memberData.getRoutes();
					for (Route r : routeList) {
						List<Point> pointList = r.getPoints();
						for (Point p : pointList) {
							List<StopInfo> stopinfoList = p.getStopInfos();
							for (StopInfo s : stopinfoList) {
								if (id == s.getId()) stopinfoList.remove(s);
							}
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (dialog != null) dialog.dismiss();

		if (success) Toast.makeText(context, "삭제가 완료되었습니다.", Toast.LENGTH_SHORT).show();
		else Toast.makeText(context, "서버와의 통신이 실패하였습니다.", Toast.LENGTH_SHORT).show();
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
		dialog = ProgressDialog.show(context, "", "삭제하는 중입니다.", true);
	}

	private JSONObject getJSON(String URL, List<NameValuePair> params) throws IOException, JSONException,
			BusAPIException {
		String paramString = URLEncodedUtils.format(params, Data.ENCODING);
		String url = URL + "?" + paramString;

		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);

		InputStream is = httpclient.execute(httpget).getEntity().getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(is, Data.ENCODING));
		StringBuilder sb = new StringBuilder();
		String line = null;
		while ((line = reader.readLine()) != null)
			sb.append(line + "\n");
		is.close();

		JSONObject result = new JSONObject(sb.toString());

		if (result.getString("success").equals("ERROR")) throw new BusAPIException(result.getString("message"));

		return result;
	}

}
